﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Kugar.Core.ExtMethod;
using Kugar.ERPFramework.BLLInterface;

namespace Kugar.ERPFramework.ServiceSystemBLL
{
    public class BLLServiceBroker:MarshalByRefObject,IDisposable
    {
        private static string _projectPath = "";
        private static Dictionary<string, object> _cacheModlule = new Dictionary<string, object>();
        private static BLLServiceBroker _defaultBLLServiceBroker = new BLLServiceBroker();

        private BLLServiceBroker()
        {}

        public IDataModuleControler GetModuleControler(string moduleName)
        {
            
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public  string ProjectPath
        {
            get { return _projectPath; }
        }

        public KeyValuePair<string, string>[] DatabaseConnectionString { private set; get; }

        public ISystemModule SystemModule
        {
            get { return (ISystemModule)GetModuleControler("System"); }
        }

        public string MainDatabaseConnectionString { get; private set; }
        public string LogDatabaseConnectionString { get; private set; }

        public void SetProject(string projectPath, string instanceID)
        {
            if (projectPath != _projectPath)
            {
                _projectPath = projectPath;
                LoadModule(_projectPath);
            }
            
            //根据实例ID,读取XML文件,读取数据库连接字符串

        }

        public static BLLServiceBroker Default
        {
            get { return _defaultBLLServiceBroker; }
        }

        private static void LoadModule(string projectPath)
        {
            var dlls = getDlls(projectPath);

            if (dlls == null || dlls.Length <= 0)
            {
                return;
            }

            foreach (var dll in dlls)
            {
                Assembly assembly = null;

                try
                {
                    assembly = Assembly.LoadFile(dll);
                }
                catch (Exception)
                {
                    continue;
                }

                var types = assembly.GetTypes();

                foreach (var type in types)
                {
                    if (type.IsSubclassOf(typeof(MarshalByRefObject)) && type.IsImplementlInterface(typeof(IDataModuleControler)))
                    {
                        var t = (IDataModuleControler)Activator.CreateInstance(type);

                        _cacheModlule.Add(t.Name, t);
                    }
                }
            }
        }

        private static string[] getDlls(string projectPath)
        {

        }


    }
}
